package common

import (
	"context"
	"github.com/afex/hystrix-go/hystrix"
	"github.com/asim/go-micro/v3/client"
	"github.com/zw2582/ginlib"
	"go.uber.org/zap"
	"net/http"
)

type hystrixClient struct {
	client.Client
}

func (this *hystrixClient)Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error  {
	//添加熔断
	return hystrix.Do(req.Service()+"."+req.Endpoint(), func() error {
		return this.Client.Call(ctx, req, rsp, opts...)
	}, func(err error) error {
		//触发熔断，可加降级操作
		ginlib.Logger.Error("触发熔断", zap.Error(err))
		return err
	})
}

func NewHystrixClientWrapper(listenAddr string) client.Wrapper {
	//添加hystrix监听
	if listenAddr != "" {
		hs := hystrix.NewStreamHandler()
		hs.Start()
		go func() {
			err := http.ListenAndServe(listenAddr, hs)
			if err != nil {
				ginlib.Logger.Error("启动hystrix监听失败")
			}
		}()
	}

	return func(c client.Client) client.Client {
		return &hystrixClient{c}
	}
}
